﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Win32;
using SqlSugar;
using System.Diagnostics;
using System.Security.Claims;
using Zhao.Common.Applet;
using Zhao.Common.Helper;
using Zhao.IServer;
using Zhao.IServer.User;
using Zhao.Models.AppletDto;
using Zhao.Models.Entity;

namespace Zhao.Arena.MiniProgram.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly WechatAPIClient _wechatAPIClient;
        private readonly IUsersServer _usersServer;
        private readonly IOrdersServer _ordersServer;

        public UserController(WechatAPIClient wechatAPIClient, IUsersServer usersServer, IOrdersServer ordersServer)
        {
            this._wechatAPIClient = wechatAPIClient;
            this._ordersServer = ordersServer;
            this._usersServer = usersServer;
        }

        [HttpPost()]
        public async Task<JsonResult> Post(RegisterRequest register)
        {
            var result = new ApiResult
            {
                Success = false,
            };
            // 1. 用code换取openid
            var wxSession = await _wechatAPIClient.GetCode2Session(register.code);

            if (wxSession == null)
            {
                result.Message = "非法用户";
                return new JsonResult(result);
            }

            //验证手机号码是否存在
            var isPhone = await _usersServer.QueryCountAsync(x => x.Phone.Equals(register.userInfo.phone));

            if (isPhone > 0)
            {
                result.Message = "手机号码已存在";
                return new JsonResult(result);
            }

            //进行非空校验
            if (register.userInfo.image.IsNullOrWhiteSpace())
            {
                result.Message = "请上传头像";
                return new JsonResult(result);
            }
            if (register.userInfo.name.IsNullOrWhiteSpace())
            {
                result.Message = "用户名不能为空";
                return new JsonResult(result);
            }

            //不存在就可以开始创建用户信息了
            Users user = new Users();

            user.Avatar = register.userInfo.image;
            user.Phone = register.userInfo.phone;
            user.Username = register.userInfo.name;
            user.Sex = register.userInfo.sex;
            user.CreatedAt = DateTime.Now;
            user.OpenID = wxSession.openid;
            user.AccountBalance = 0;

            bool isAdd = await _usersServer.AddAsync(user) > 0;

            if (isAdd)
            {
                result.Success = true;
                result.Message = "成功";
            }
            else result.Message = "操作失败，请稍后再试";


            return new JsonResult(result);
        }

        [HttpPut()]
        [Authorize]
        public async Task<JsonResult> UpdateUserInfo([FromBody] RegisterRequest updateRequest)
        {
            var result = new ApiResult { Success = false };

            // --- 1. 身份验证：通过微信OpenID验证用户身份 ---
            // 1. 用code换取openid
            var wxSession = await _wechatAPIClient.GetCode2Session(updateRequest.code);

            if (wxSession == null)
            {
                result.Message = "非法用户";
                return new JsonResult(result);
            }

            // 根据OpenID查询要修改的用户
            var existingUser = await _usersServer.QueryAsync(u => u.OpenID == wxSession.openid);
            if (existingUser == null)
            {
                result.Message = "用户不存在或未授权";
                return new JsonResult(result);
            }

            // --- 2. 数据校验 ---
            // 非空校验
            if (updateRequest.userInfo.image.IsNullOrWhiteSpace())
            {
                result.Message = "请上传头像";
                return new JsonResult(result);
            }
            if (updateRequest.userInfo.name.IsNullOrWhiteSpace())
            {
                result.Message = "用户名不能为空";
                return new JsonResult(result);
            }

            // --- 3. 防越权修改：禁止修改OpenID、手机号等核心字段 ---
            // 仅允许修改头像、用户名、性别
            existingUser.Avatar = updateRequest.userInfo.image;
            existingUser.Username = updateRequest.userInfo.name;
            existingUser.Sex = updateRequest.userInfo.sex;
            existingUser.Phone= updateRequest.userInfo.phone;

            // --- 4. 执行更新 ---
            bool isUpdated = await _usersServer.UpdateAsync(existingUser);

            if (isUpdated)
            {
                result.Success = true;
                result.Message = "修改成功";
            }
            else
            {
                result.Message = "修改失败，请稍后重试";
            }

            return new JsonResult(result);
        }




    }
}
